package gongshw.xml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.*;

public class XmlHandler {
	private Document doc;
	
	public Document getDocument(){
		return doc;
	}
	
	public XmlHandler(String text)throws DocumentException{
		doc = XmlManager.getXML(text);
	}
	
	public String getAttribute(String ele,String att){
		Element root = doc.getRootElement();
		if(root.getName().equals(ele))
			return root.attribute(att).getText();
	    for ( Iterator i = root.elementIterator(ele); i.hasNext();) {
	        Element foo = (Element) i.next();
	        return foo.attribute(att).getText();
	     }
		return null;
	}
	
	public String getText(String ele){
		Element root = doc.getRootElement();
		if(root.getName().equals(ele))
			return root.getText();
	    for ( Iterator i = root.elementIterator(ele); i.hasNext();) {
	        Element foo = (Element) i.next();
	        return foo.getText();
	     }
		return null;
	}
	
	public Element[] getElementArray(String eleName){
		List<Element> eleList = new ArrayList<Element>();
		try{
			addElementTo(doc.getRootElement(),eleName,eleList);
		}catch(NullPointerException e){
			System.out.println(doc);
		}
		Element[] eleArray = new Element[eleList.size()];
		eleList.toArray(eleArray);
		return eleArray;
	}
	
	private void addElementTo(Element ele,String name,List<Element> eleList){
		Element root = ele;
		if(root.getName().equals(name))
			eleList.add(root);
	    for ( Iterator i = root.elementIterator(); i.hasNext();) {
	        Element foo = (Element) i.next();
	        addElementTo(foo,name,eleList);
	     }
	}
}
